package net.wanho.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import lombok.SneakyThrows;
import net.wanho.po.User;
import net.wanho.po.UserInfo;
import net.wanho.vo.R;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2024-10-25 15:10
 * Description：<描述>
 */
@RestController
public class EasyPOIController {

    @SneakyThrows
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        List<User> list = new ArrayList<>();
        list.add(new User(1, "张三", "123",  "13888888888", "北京", new Date(), 1));
        list.add(new User(2, "李四", "123", "13888888888", "上海", new Date(), 1));
        list.add(new User(3, "王五", "123", "13888888888", "广州", new Date(), 0));
        list.add(new User(4, "赵六", "123", "13888888888", "深圳", new Date(), 0));
        list.add(new User(5, "田七", "123", "13888888888", "杭州", new Date(), 1));

        ExportParams params = new ExportParams("用户信息表", "用户表");
        Workbook workbook = ExcelExportUtil.exportExcel(params, User.class, list);

        // 设置响应内容类型为excel
        response.setContentType("application/vnd.ms-excel");
        // 设置响应的文件名
        response.setHeader("Content-Disposition", "attachment;filename="+new String("用户信息表.xls".getBytes("utf-8"),"iso-8859-1"));
        // 将Excel写入响应流中
        workbook.write(response.getOutputStream());
    }


    @SneakyThrows
    @PostMapping("import")
    public R importExcel(@RequestParam("file") MultipartFile file){
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<User> list = ExcelImportUtil.importExcel(file.getInputStream(), User.class, params);

        list.forEach(System.out::println);

        return R.success();
    }
}
